<template>
  <div class="statistics">
    <el-alert
      v-if="showAuthError"
      title="认证已过期，请重新登录"
      type="error"
      description="您的登录状态已失效，请刷新页面或重新登录"
      show-icon
      closable
      @close="showAuthError = false"
    >
      <template #default>
        <div class="alert-actions">
          <el-button size="small" @click="reloadPage">刷新页面</el-button>
          <el-button size="small" type="primary" @click="goToLogin">重新登录</el-button>
        </div>
      </template>
    </el-alert>
    
    <div class="time-select">
      <el-tabs v-model="activeTab" class="time-tabs" @tab-click="handleTabChange">
        <el-tab-pane label="昨日" name="yesterday" />
        <el-tab-pane label="近7日" name="week" />
        <el-tab-pane label="近30日" name="month" />
        <el-tab-pane label="本周" name="thisWeek" />
        <el-tab-pane label="本月" name="thisMonth" />
        <el-tab-pane label="自定义时间" name="custom">
          <template #label>
            <span>已选时间：{{ dateRange[0] }} 至 {{ dateRange[1] }}</span>
          </template>
        </el-tab-pane>
      </el-tabs>

      <div v-if="activeTab === 'custom'" class="date-picker-container">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </div>
    </div>

    <div class="statistics-cards" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="24" v-if="!hasValidToken" class="mb-20">
          <el-card shadow="hover">
            <div class="login-prompt">
              <el-icon class="warning-icon"><WarningFilled /></el-icon>
              <p>登录状态已失效，请重新登录</p>
              <el-button type="primary" @click="goToLogin">立即登录</el-button>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>营业额统计</span>
              </div>
            </template>
            <div class="chart-container" ref="revenueChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>用户统计</span>
              </div>
            </template>
            <div class="chart-container" ref="userChartRef"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>订单统计</span>
                <div class="order-rate">
                  <span>订单完成率</span>
                  <span class="order-completion-rate">{{ completionRate }}%</span>
                </div>
              </div>
            </template>
            <div class="chart-container" ref="orderChartRef"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="statistics-table" v-loading="topLoading">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>销量排名TOP10</span>
            <el-button type="primary" size="small" plain @click="refreshTopData" :loading="topLoading">
              <el-icon class="mr-5"><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </template>
        <div class="top-chart-container">
          <div v-if="topLoading" class="loading-placeholder">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>正在加载数据...</p>
          </div>
          <div v-else-if="!top10Data.nameList || !top10Data.nameList.length" class="empty-placeholder">
            <el-empty description="暂无销量数据"></el-empty>
          </div>
          <div v-else class="top10-chart" id="top10Chart" ref="top10ChartRef"></div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage, ElEmpty } from 'element-plus'
import { Loading, Refresh, WarningFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getTurnoverStatistics, getUserStatistics, getOrdersStatistics, getTop10 } from '@/api/statistics'

// 获取路由实例
const router = useRouter()

// 状态变量
const activeTab = ref('week')
const dateRange = ref(['', ''])
const loading = ref(false)
const topLoading = ref(false)
const showAuthError = ref(false)
const completionRate = ref('0.0')

// 图表DOM引用
const revenueChartRef = ref(null)
const userChartRef = ref(null)
const orderChartRef = ref(null)
const top10ChartRef = ref(null)

// 图表实例
let revenueChart = null
let userChart = null
let orderChart = null
let top10Chart = null

// 数据状态
const top10Data = ref({
  nameList: [],
  numberList: []
})
const turnoverData = ref({
  dateList: [],
  numberList: []
})
const userStatistics = ref({
  dateList: [],
  totalUserList: [],
  newUserList: []
})
const orderStatistics = ref({
  dateList: [],
  orderCountList: [],
  validOrderCountList: []
})

// 根据token的存在判断是否有效
const hasValidToken = computed(() => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  return !!token
})

// 检查认证状态
const checkAuthentication = () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    console.warn('未找到认证令牌')
    showAuthError.value = true
    return false
  }
  return true
}

// 刷新页面
const reloadPage = () => {
  window.location.reload()
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/login')
}

// 获取当前日期
const getToday = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取昨天日期
const getYesterday = () => {
  const date = new Date()
  date.setDate(date.getDate() - 1)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取近7天的开始日期
const get7DaysAgo = () => {
  const date = new Date()
  date.setDate(date.getDate() - 7)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取近30天的开始日期
const get30DaysAgo = () => {
  const date = new Date()
  date.setDate(date.getDate() - 30)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取本周的开始日期
const getWeekStart = () => {
  const date = new Date()
  const day = date.getDay() || 7
  date.setDate(date.getDate() - day + 1)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const dateDay = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${dateDay}`
}

// 获取本月的开始日期
const getMonthStart = () => {
  const date = new Date()
  date.setDate(1)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 初始化日期范围
const initDateRange = () => {
  dateRange.value = [get7DaysAgo(), getToday()]
}

// 处理标签页切换
const handleTabChange = (tab) => {
  switch (tab.props.name) {
    case 'yesterday':
      dateRange.value = [getYesterday(), getYesterday()]
      break
    case 'week':
      dateRange.value = [get7DaysAgo(), getToday()]
      break
    case 'month':
      dateRange.value = [get30DaysAgo(), getToday()]
      break
    case 'thisWeek':
      dateRange.value = [getWeekStart(), getToday()]
      break
    case 'thisMonth':
      dateRange.value = [getMonthStart(), getToday()]
      break
    // custom保持原有时间范围不变
  }
  
  // 加载数据
  fetchAllData()
}

// 日期范围变化处理
const handleDateRangeChange = () => {
  if (dateRange.value && dateRange.value.length === 2) {
    fetchAllData()
  }
}

// 获取所有统计数据
const fetchAllData = async () => {
  if (!hasValidToken.value) {
    ElMessage.warning('请先登录后再获取数据')
    return
  }
  
  loading.value = true
  topLoading.value = true
  
  try {
    // 准备日期参数
    const begin = dateRange.value[0]
    const end = dateRange.value[1]
    
    if (!begin || !end) {
      ElMessage.warning('请选择日期范围')
      return
    }
    
    // 并行请求所有数据
    const results = await Promise.allSettled([
      fetchTurnoverData(begin, end),
      fetchUserData(begin, end),
      fetchOrderData(begin, end),
      fetchTop10Data(begin, end)
    ])
    
    console.log('所有数据加载结果:', results.map(r => r.status))
    
    // 检查是否所有请求都已完成（无论成功或失败）
    const allCompleted = results.every(r => r.status === 'fulfilled' || r.status === 'rejected')
    
    if (!allCompleted) {
      console.warn('部分数据请求未完成')
    }
    
    // 渲染所有图表，使用setTimeout确保DOM已更新
    setTimeout(() => {
      nextTick(() => {
        try {
          renderAllCharts()
        } catch (e) {
          console.error('渲染图表失败:', e)
        }
      })
    }, 100)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取统计数据失败，请刷新重试')
  } finally {
    loading.value = false
    topLoading.value = false
  }
}

// 获取营业额数据
const fetchTurnoverData = async (begin, end) => {
  try {
    const result = await getTurnoverStatistics(begin, end)
    console.log('营业额数据:', result)
    
    // 处理API返回的数据
    if (result) {
      // API返回的是逗号分隔的字符串，需要转换为数组
      const dateList = result.dateList ? result.dateList.split(',') : []
      const numberList = result.turnoverList ? result.turnoverList.split(',').map(Number) : []
      
      turnoverData.value = { dateList, numberList }
    }
    return result
  } catch (error) {
    console.error('获取营业额数据失败:', error)
    // 返回备用数据以防API调用失败
    fallbackTurnoverData()
    return null
  }
}

// 获取用户统计数据
const fetchUserData = async (begin, end) => {
  try {
    const result = await getUserStatistics(begin, end)
    console.log('用户统计数据:', result)
    
    // 处理API返回的数据
    if (result) {
      // API返回的是逗号分隔的字符串，需要转换为数组
      const dateList = result.dateList ? result.dateList.split(',') : []
      const totalUserList = result.totalUserList ? result.totalUserList.split(',').map(Number) : []
      const newUserList = result.newUserList ? result.newUserList.split(',').map(Number) : []
      
      userStatistics.value = { dateList, totalUserList, newUserList }
    }
    return result
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
    // 返回备用数据以防API调用失败
    fallbackUserData()
    return null
  }
}

// 获取订单统计数据
const fetchOrderData = async (begin, end) => {
  try {
    const result = await getOrdersStatistics(begin, end)
    console.log('订单统计数据:', result)
    
    // 处理API返回的数据
    if (result) {
      // API返回的是逗号分隔的字符串，需要转换为数组
      const dateList = result.dateList ? result.dateList.split(',') : []
      const orderCountList = result.orderCountList ? result.orderCountList.split(',').map(Number) : []
      const validOrderCountList = result.validOrderCountList ? result.validOrderCountList.split(',').map(Number) : []
      
      orderStatistics.value = { dateList, orderCountList, validOrderCountList }
      
      // 设置订单完成率
      completionRate.value = result.orderCompletionRate ? (result.orderCompletionRate * 100).toFixed(1) : '0.0'
    }
    return result
  } catch (error) {
    console.error('获取订单统计数据失败:', error)
    // 返回备用数据以防API调用失败
    fallbackOrderData()
    return null
  }
}

// 获取销量TOP10数据
const fetchTop10Data = async (begin, end) => {
  try {
    const result = await getTop10(begin, end)
    console.log('销量TOP10数据:', result)
    
    // 处理API返回的数据
    if (result) {
      // API返回的是逗号分隔的字符串，需要转换为数组
      const nameList = result.nameList ? result.nameList.split(',') : []
      const numberList = result.numberList ? result.numberList.split(',').map(Number) : []
      
      // 检查是否有数据
      if (nameList.length === 0 || numberList.length === 0) {
        console.warn('服务端返回的TOP10数据为空，使用备用数据')
        fallbackTop10Data()
        return result
      }
      
      // 按照图表需要的格式，数组需要倒序显示（从小到大）
      top10Data.value = {
        nameList: nameList.slice().reverse(),
        numberList: numberList.slice().reverse()
      }
    } else {
      // 如果没有返回结果，使用备用数据
      fallbackTop10Data()
    }
    return result
  } catch (error) {
    console.error('获取销量TOP10数据失败:', error)
    // 返回备用数据以防API调用失败
    fallbackTop10Data()
    return null
  }
}

// 备用营业额数据（API调用失败时使用）
const fallbackTurnoverData = () => {
  const fallbackDates = ['2025-05-16', '2025-05-17', '2025-05-18', '2025-05-19', '2025-05-20', '2025-05-21', '2025-05-22']
  turnoverData.value = {
    dateList: fallbackDates,
    numberList: [500, 600, 550, 650, 700, 680, 720]
  }
  ElMessage.warning('使用备用营业额数据 - 请检查后端连接')
}

// 备用用户数据（API调用失败时使用）
const fallbackUserData = () => {
  const fallbackDates = ['2025-05-16', '2025-05-17', '2025-05-18', '2025-05-19', '2025-05-20', '2025-05-21', '2025-05-22']
  userStatistics.value = {
    dateList: fallbackDates,
    totalUserList: [1000, 1015, 1032, 1047, 1063, 1078, 1095],
    newUserList: [10, 15, 17, 15, 16, 15, 17]
  }
  ElMessage.warning('使用备用用户数据 - 请检查后端连接')
}

// 备用订单数据（API调用失败时使用）
const fallbackOrderData = () => {
  const fallbackDates = ['2025-05-16', '2025-05-17', '2025-05-18', '2025-05-19', '2025-05-20', '2025-05-21', '2025-05-22']
  orderStatistics.value = {
    dateList: fallbackDates,
    orderCountList: [25, 22, 20, 28, 24, 21, 23],
    validOrderCountList: [20, 18, 16, 25, 20, 18, 20]
  }
  
  // 计算订单完成率
  calculateCompletionRate()
  ElMessage.warning('使用备用订单数据 - 请检查后端连接')
}

// 备用销量排名TOP10数据（API调用失败时使用）
const fallbackTop10Data = () => {
  console.log('使用TOP10备用数据')
  const testNames = ['宫保鸡丁', '麻婆豆腐', '水煮鱼片', '回锅肉', '鱼香肉丝', '东坡肉', '糖醋里脊', '京酱肉丝', '香辣虾', '蒜蓉蒸虾']
  const testNumbers = [120, 110, 108, 106, 98, 92, 90, 87, 85, 82]
  
  top10Data.value = {
    nameList: testNames.slice().reverse(),
    numberList: testNumbers.slice().reverse()
  }
  
  console.log('生成的TOP10备用数据:', top10Data.value)
  ElMessage.warning('使用备用销量排名数据 - 请检查后端连接')
}

// 计算订单完成率
const calculateCompletionRate = () => {
  try {
    let validOrderCount = 0
    let totalOrderCount = 0
    
    // 确保是数组并且有数据
    if (Array.isArray(orderStatistics.value.validOrderCountList) && orderStatistics.value.validOrderCountList.length > 0) {
      validOrderCount = orderStatistics.value.validOrderCountList.reduce((sum, val) => sum + (Number(val) || 0), 0)
    }
    
    // 确保是数组并且有数据
    if (Array.isArray(orderStatistics.value.orderCountList) && orderStatistics.value.orderCountList.length > 0) {
      totalOrderCount = orderStatistics.value.orderCountList.reduce((sum, val) => sum + (Number(val) || 0), 0)
    }
    
    // 计算订单完成率，避免除零错误
    if (totalOrderCount > 0) {
      completionRate.value = (validOrderCount / totalOrderCount * 100).toFixed(1)
    } else {
      completionRate.value = '0.0'
    }
  } catch (error) {
    console.error('计算订单完成率出错:', error)
    completionRate.value = '0.0'
  }
}

// 渲染所有图表
const renderAllCharts = () => {
  try {
    // 检查并渲染各个图表
    if (revenueChartRef.value) {
      renderTurnoverChart()
    } else {
      console.warn('营业额图表容器不存在')
    }
    
    if (userChartRef.value) {
      renderUserChart()
    } else {
      console.warn('用户统计图表容器不存在')
    }
    
    if (orderChartRef.value) {
      renderOrderChart()
    } else {
      console.warn('订单统计图表容器不存在')
    }
    
    // TOP10图表使用ID选择器
    renderTop10Chart()
  } catch (error) {
    console.error('渲染图表失败:', error)
  }
}

// 渲染营业额统计图表
const renderTurnoverChart = () => {
  // 确保DOM元素存在
  if (!revenueChartRef.value) {
    console.warn('营业额图表容器不存在')
    return
  }
  
  try {
    // 销毁之前的实例
    if (revenueChart) {
      revenueChart.dispose()
    }
    
    // 初始化图表
    revenueChart = echarts.init(revenueChartRef.value)
    
    // 设置图表配置
    revenueChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        },
        formatter: '{b}<br>营业额: {c}元'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: turnoverData.value.dateList || [],
        axisLine: {
          lineStyle: {
            color: '#909399'
          }
        },
        axisLabel: {
          color: '#606266'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#606266',
          formatter: '{value}'
        },
        splitLine: {
          lineStyle: {
            color: '#EBEEF5'
          }
        }
      },
      series: [
        {
          data: turnoverData.value.numberList || [],
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#FFB800'
          },
          lineStyle: {
            color: '#FFB800',
            width: 2
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                {offset: 0, color: 'rgba(255, 184, 0, 0.3)'},
                {offset: 1, color: 'rgba(255, 184, 0, 0.1)'}
              ]
            )
          }
        }
      ]
    }, true) // 添加第二个参数true，表示不合并
  } catch (error) {
    console.error('渲染营业额图表失败:', error)
    ElMessage.error(`渲染营业额图表错误: ${error.message}`)
  }
}

// 渲染用户统计图表
const renderUserChart = () => {
  // 确保DOM元素存在
  if (!userChartRef.value) {
    console.warn('用户统计图表容器不存在')
    return
  }
  
  try {
    // 销毁之前的实例
    if (userChart) {
      userChart.dispose()
    }
    
    // 初始化图表
    userChart = echarts.init(userChartRef.value)
    
    // 设置图表配置
    userChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      legend: {
        data: ['用户总量', '新增用户'],
        right: 0,
        textStyle: {
          color: '#606266'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: userStatistics.value.dateList || [],
        axisLine: {
          lineStyle: {
            color: '#909399'
          }
        },
        axisLabel: {
          color: '#606266'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#606266'
        },
        splitLine: {
          lineStyle: {
            color: '#EBEEF5'
          }
        }
      },
      series: [
        {
          name: '用户总量',
          type: 'line',
          data: userStatistics.value.totalUserList || [],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#FFB800'
          },
          lineStyle: {
            color: '#FFB800',
            width: 2
          }
        },
        {
          name: '新增用户',
          type: 'line',
          data: userStatistics.value.newUserList || [],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#F56C6C'
          },
          lineStyle: {
            color: '#F56C6C',
            width: 2
          }
        }
      ]
    }, true) // 添加第二个参数true，表示不合并
  } catch (error) {
    console.error('渲染用户图表失败:', error)
    ElMessage.error(`渲染用户图表错误: ${error.message}`)
  }
}

// 渲染订单统计图表
const renderOrderChart = () => {
  // 确保DOM元素存在
  if (!orderChartRef.value) {
    console.warn('订单统计图表容器不存在')
    return
  }
  
  try {
    // 销毁之前的实例
    if (orderChart) {
      orderChart.dispose()
    }
    
    // 初始化图表
    orderChart = echarts.init(orderChartRef.value)
    
    // 设置图表配置
    orderChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'line'
        }
      },
      legend: {
        data: ['订单总数', '有效订单'],
        right: 0,
        textStyle: {
          color: '#606266'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: orderStatistics.value.dateList || [],
        axisLine: {
          lineStyle: {
            color: '#909399'
          }
        },
        axisLabel: {
          color: '#606266'
        }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: false
        },
        axisLabel: {
          color: '#606266'
        },
        splitLine: {
          lineStyle: {
            color: '#EBEEF5'
          }
        }
      },
      series: [
        {
          name: '订单总数',
          type: 'line',
          data: orderStatistics.value.orderCountList || [],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#E6A23C'
          },
          lineStyle: {
            color: '#E6A23C',
            width: 2
          }
        },
        {
          name: '有效订单',
          type: 'line',
          data: orderStatistics.value.validOrderCountList || [],
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          itemStyle: {
            color: '#F56C6C'
          },
          lineStyle: {
            color: '#F56C6C',
            width: 2
          }
        }
      ]
    }, true) // 添加第二个参数true，表示不合并
  } catch (error) {
    console.error('渲染订单图表失败:', error)
    ElMessage.error(`渲染订单图表错误: ${error.message}`)
  }
}

// 渲染销量排名TOP10图表
const renderTop10Chart = () => {
  try {
    // 检查数据是否存在并且有效
    if (!top10Data.value.nameList || !top10Data.value.nameList.length) {
      console.warn('TOP10数据为空，无法渲染图表')
      fallbackTop10Data() // 使用备用数据
    }
    
    // 确保此时有数据可用
    if (!top10Data.value.nameList || !top10Data.value.nameList.length) {
      console.error('无法获取有效的TOP10数据')
      return
    }
    
    // 获取DOM元素 - 优先使用ref，其次使用id选择器
    let chartDom = top10ChartRef.value
    if (!chartDom) {
      chartDom = document.getElementById('top10Chart')
      if (!chartDom) {
        console.error('找不到TOP10图表DOM元素')
        return
      }
    }
    
    // 检查容器大小
    const domWidth = chartDom.clientWidth
    const domHeight = chartDom.clientHeight
    
    if (domWidth === 0 || domHeight === 0) {
      console.warn('TOP10图表容器尺寸为0，等待DOM更新后重试')
      // 使用setTimeout等待DOM更新
      setTimeout(() => {
        renderTop10Chart()
      }, 200)
      return
    }
    
    // 销毁之前的实例
    if (top10Chart) {
      top10Chart.dispose()
      top10Chart = null
    }
    
    // 初始化图表
    top10Chart = echarts.init(chartDom)
    console.log('TOP10图表实例已创建:', !!top10Chart)
    
    // 创建图表配置
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        top: 10,
        left: 60,
        right: 60,
        bottom: 10,
        containLabel: true
      },
      xAxis: {
        type: 'value',
        show: false
      },
      yAxis: {
        type: 'category',
        data: top10Data.value.nameList,
        axisLine: { show: false },
        axisTick: { show: false },
        axisLabel: {
          color: '#666',
          fontSize: 12
        }
      },
      series: [
        {
          name: '销量',
          type: 'bar',
          data: top10Data.value.numberList,
          showBackground: true,
          backgroundStyle: {
            color: '#F3F4F7'
          },
          barWidth: 20,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#FFD000' },
              { offset: 1, color: '#FFBD00' }
            ]),
            borderRadius: [0, 10, 10, 0]
          },
          label: {
            show: true,
            position: 'right',
            color: '#333'
          }
        }
      ]
    }
    
    // 应用图表配置
    top10Chart.setOption(option, true) // 添加第二个参数true，表示不合并
    
    // 添加一次resize以确保正确显示
    setTimeout(() => {
      try {
        if (top10Chart) {
          top10Chart.resize()
        }
      } catch (e) {
        console.error('TOP10图表resize失败:', e)
      }
    }, 100)
  } catch (error) {
    console.error('渲染TOP10图表出错:', error)
    ElMessage.error(`渲染TOP10图表失败: ${error.message}`)
  }
}

// 刷新销量排名数据
const refreshTopData = () => {
  console.log('手动刷新销量排名数据')
  topLoading.value = true
  
  const begin = dateRange.value[0]
  const end = dateRange.value[1]
  
  if (!begin || !end) {
    ElMessage.warning('请选择日期范围')
    topLoading.value = false
    return
  }
  
  fetchTop10Data(begin, end).finally(() => {
    // 使用nextTick确保DOM已更新
    nextTick(() => {
      renderTop10Chart()
      topLoading.value = false
    })
  })
}

// 监听窗口大小变化，调整图表尺寸
const handleResize = () => {
  // 使用nextTick确保DOM已更新
  nextTick(() => {
    if (revenueChart) {
      try {
        revenueChart.resize()
      } catch (e) {
        console.error('营业额图表调整大小失败:', e)
      }
    }
    if (userChart) {
      try {
        userChart.resize()
      } catch (e) {
        console.error('用户图表调整大小失败:', e)
      }
    }
    if (orderChart) {
      try {
        orderChart.resize()
      } catch (e) {
        console.error('订单图表调整大小失败:', e)
      }
    }
    if (top10Chart) {
      try {
        top10Chart.resize()
      } catch (e) {
        console.error('TOP10图表调整大小失败:', e)
      }
    }
  })
}

// 组件挂载时
onMounted(() => {
  // 初始化日期范围
  initDateRange()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
  
  // 延迟加载数据，确保DOM完全渲染
  setTimeout(() => {
    // 使用nextTick确保DOM已渲染
    nextTick(() => {
      // 检查认证状态并请求数据
      if (checkAuthentication()) {
        // 获取数据
        fetchAllData()
      }
    })
  }, 300) // 添加延迟确保DOM已完全渲染
})

// 组件卸载时
onUnmounted(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  if (revenueChart) revenueChart.dispose()
  if (userChart) userChart.dispose()
  if (orderChart) orderChart.dispose()
  if (top10Chart) top10Chart.dispose()
})
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.time-select {
  margin-bottom: 20px;
}

.time-tabs {
  margin-bottom: 10px;
}

.date-picker-container {
  margin-bottom: 10px;
  display: flex;
  justify-content: flex-end;
}

.statistics-cards {
  margin-bottom: 20px;
}

.statistics-table {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-rate {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.order-completion-rate {
  color: #F56C6C;
  font-weight: bold;
  margin-left: 5px;
}

/* 增大图表容器高度并确保显示 */
.chart-container {
  height: 300px !important;
  width: 100% !important;
  min-height: 300px;
  display: block !important;
  visibility: visible !important;
}

.top-chart-container {
  position: relative;
  height: 400px;
  width: 100%;
  min-height: 400px;
}

.top10-chart {
  height: 400px !important;
  width: 100% !important;
  min-height: 400px;
  display: block !important;
  visibility: visible !important;
}

.loading-placeholder,
.empty-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.loading-placeholder .el-icon {
  font-size: 40px;
  margin-bottom: 15px;
  color: #409EFF;
}

.loading-placeholder p {
  font-size: 14px;
}

.alert-actions {
  margin-top: 10px;
}

.mb-20 {
  margin-bottom: 20px;
}

.mr-5 {
  margin-right: 5px;
}

.login-prompt {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  text-align: center;
}

.warning-icon {
  font-size: 48px;
  color: #E6A23C;
  margin-bottom: 15px;
}

.login-prompt p {
  font-size: 16px;
  margin-bottom: 15px;
  color: #606266;
}

/* 响应式布局 */
@media screen and (max-width: 1366px) {
  .chart-container {
    height: 250px;
  }
  
  .top10-chart {
    height: 350px;
  }
}

/* 针对移动设备的响应式布局 */
@media screen and (max-width: 768px) {
  :deep(.el-row) {
    flex-direction: column;
  }
  
  :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 15px;
  }
  
  .chart-container, 
  .top10-chart {
    height: 200px;
  }
}
</style> 